AOP – Logging all method calls and executions in Java with AspectJ

This is not a walk-thru. This is just an example AspectJ class.

Note: For logging, the log singleton which I previously posted is used, but of course you can hook this up to your own logging methods or just print to the console.

This class is intended to log when a method executes and when a method ends. Methods inside are tabbed.

package mainExample;

import org.aspectj.lang.JoinPoint;

public aspect AspectLogMethodExecution
{
	private int tabCount = 0;

	pointcut AnyMethod() : (call(* *.*(..)) || execution(* *.*(..)))
						&& !within(AspectLogMethodExecution)
						&& !within(Log);

	before() : AnyMethod()
	{
		PrintMethod(thisJoinPointStaticPart);
		tabCount++;
	}

	after() : AnyMethod()
	{
		tabCount--;
		PrintMethod(thisJoinPointStaticPart);
	}

	private void PrintMethod(JoinPoint.StaticPart inPart)
	{
		Log.WriteLine(GetTabs() + inPart);
	}

	private String GetTabs()
	{
		String tabs = "";
		for (int i = 0; i < tabCount; i++)
		{
			tabs += "\t";
		}
		return tabs;
	}
}

So if you have a simple Hello, World app, this is the log output.

execution(void mainExample.Main.main(String[]))
	call(void java.io.PrintStream.println(String))
	call(void java.io.PrintStream.println(String))
execution(void mainExample.Main.main(String[]))

Return to Aspected Oriented Programming – Examples

One Comment

  1. [...] This class is intended to log when a method executes and when a method ends and include the time it took for a method to execute in nanoseconds. Methods inside methods are tabbed. This is an enhancement to this post: AOP – Logging all method calls and executions [...]

Leave a Reply

How to post code in comments?